#include <REGX52.H>
#include "Delay.h"
#include "Timer0.h"

sbit BUZZER = P2^5;
#define SPEED 400
unsigned int freq_table[] = {
    0, 
    63628, 63731, 63835, 63928, 64021, 64103, 64185, 64260, 64331, 64400, 64463, 64524, 
    64580, 64633, 64684, 64732, 64777, 64820, 64860, 64898, 64934, 64968, 65000, 65030, 
    65058, 65085, 65110, 65134, 65157, 65178, 65198, 65217, 65235, 65252, 65268, 65283
};
// 第2个数代表时长，以4分音符为基准500ms
// 加code后存入Flash(ROM)中，但只读
unsigned char code music[] = {
    6, 4,
    6, 2,
    13, 4,
    13, 4,
    12, 4,
    10, 4,
    12, 4 + 4,
    8, 4,
    8, 2,
    12, 4,
    12, 4,
    13, 4,
    8, 4,
    10, 8,
    6, 4,
    6, 2,
    8, 4,
    10, 4,
    8, 4,
    8, 4,
    6, 8,
    3, 8,
    5, 8,
    0xFF};
unsigned char freq_select, music_select;

void main()
{
    Timer0Init();
	while (1)
	{
        if (music[music_select] != 0xFF)
        {
            freq_select = music[music_select];
            music_select++;
            Delay(SPEED / 4 * music[music_select]);
            music_select++;
            TR0 = 0;
            Delay(5);
            TR0 = 1;
        }
        else
        {
            TR0 = 0;
            while (1) {}
        }
	}
}

void Timer0_Rountine(void) interrupt 1
{
    // 休止符写法，频率不是0才振荡发声
    if (freq_table[freq_select])
    {
        TL0 = freq_table[freq_select] % 256;		//设置定时初始值
        TH0 = freq_table[freq_select] / 256;		//设置定时初始值
        BUZZER = !BUZZER;  // 1us中断一次，则buzzer频率500Hz
    }
    
}